﻿using System;
using System.Collections.Generic;
using System.Text;
using log4net;
using Scenario.WAPI.Exception;
using Scenario.WorkflowEngine.DataModel.WorkflowRelevantData;
using Scenario.WorkflowEngine.DataModel.WorkflowProcesses;
using Scenario.WAPI;

namespace Scenario.WorkflowEngine
{
    public class EngineException : Exception 
    {
       public EngineException(string sMsgErr) :base(sMsgErr)
		{
		}
    }

    public class Engine
    {
        private static readonly Engine _instance = new Engine();

        //Criteria, Scheduler e Logger manager
        Scenario.WAPI.Session criteriaSession = new Scenario.WAPI.Session();
        Scenario.WorkflowEngine.Scheduler.JobManager jobManager = null;
        private static ILog logger = LogManager.GetLogger(typeof(Engine));

        private Engine() 
        {
        }

        public static Engine Instance
        {
            get
            {
                return _instance;
            }
        }

        #region Get Manager

        public Scenario.WorkflowEngine.Scheduler.JobManager Scheduler {get { return jobManager; }}
        
        #endregion

        #region Start&Stop
        public void StartUp(String sConfigurationFile, Boolean bStartScheduler)
        {
            logger.Info("Starting Criteria");

            try
            {
                criteriaSession.Start(sConfigurationFile);
            }
            catch (WAPI.Exception.WAPIException err)
            {
                throw new EngineException(err.Message);
            }

            if (bStartScheduler)
            {
                logger.Info("Starting Scheduler");
                jobManager = new Scenario.WorkflowEngine.Scheduler.JobManager();
                jobManager.StartListener();
            }
        }

        public void ShutDown()
        {
            if (jobManager != null)
            {
                logger.Info("Stopping Scheduler");
                jobManager.Stop();
            }

            logger.Info("Stopping Process Engine");
            try
            {
                criteriaSession.End();
            }
            catch (WAPI.Exception.WAPIException err)
            {
                throw new EngineException(err.Message);
            }
        }

        #endregion
        
        #region Helpers

        public static ProcessHelper ProcessHelper { get { return new ProcessHelper();}}
        public static ActivityHelper ActivityHelper { get { return new ActivityHelper(); } }
        public static ApplicationHelper ApplicationHelper { get { return new ApplicationHelper(); } }
        public static DataTypesHelper DataTypesHelper { get { return new DataTypesHelper(); } }
        public static FolderHelper FolderHelper { get { return new FolderHelper(); } }
        public static UserHelper UserHelper { get { return new UserHelper(); } }
        #endregion

    }
}
